package com.hyj.serve.manage.configure.filter;

import cn.hutool.core.util.StrUtil;
import com.hyj.serve.manage.configure.properties.AppProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Order(1)
@Component
@WebFilter(filterName = "loginFilter", urlPatterns = "/**")
public class LoginFilter implements Filter {

    public static final String IS_LOGIN = "is_login";

    @Autowired
    private AppProperties appProperties;

    private static final List<String> ignoredList = Arrays.asList(
            "/login"
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(StrUtil.isEmpty(appProperties.getPassword())){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        AntPathMatcher matcher = new AntPathMatcher();
        for (String path : ignoredList) {
            if(matcher.match(path, req.getServletPath())){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();
        Object attribute = session.getAttribute(IS_LOGIN);
        if(attribute == null){
//            throw new ServiceException("未登录").httpStatus(HttpStatus.UNAUTHORIZED);
            res.setStatus(401);
            return;
        }
        try {
            boolean bool = Boolean.parseBoolean(attribute.toString());
            if(bool){
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
//                throw new ServiceException("未登录").httpStatus(HttpStatus.UNAUTHORIZED);
                res.setStatus(401);
            }
        } catch (Exception e){
            log.error("拦截器错误", e);
//            throw new ServiceException("未登录").httpStatus(HttpStatus.UNAUTHORIZED);
            res.setStatus(401);
        }

    }

}